<template>
    <div class="product-add">
        <!--form表单-->
        <el-form size="small" ref="form" :model="form" v-loading="loading" label-width="200px">
            <div class="common-form">
                {{ editId ? '编辑抵扣券': '添加抵扣券'}}
            </div>
            <el-form-item label="优惠券名称" prop="name" :rules="[{ required: true, message: '请填写优惠券名称' }]">
                <el-input class="max-w460" v-model="form.name" placeholder="请输入优惠券名称"></el-input>
                <div class="tips">例如：满100减10</div>
            </el-form-item>
            <el-form-item label="优惠券颜色" :rules="[{ required: true, message: '选择优惠券颜色' }]">
                <el-radio-group v-model="form.color">
                    <el-radio :label="10" border>蓝色</el-radio>
                    <el-radio :label="20" border>红色</el-radio>
                    <el-radio :label="30" border>紫色</el-radio>
                    <el-radio :label="40" border>黄色</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="优惠券类型" :rules="[{ required: true, message: '选择优惠券类型' }]">
                <el-radio-group v-model="form.couponType">
                    <el-radio :label="item.value" v-for="item in couponOptions" :key="item.name" border>
                        {{ item.name }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <div v-if="form.couponType == 10 || form.couponType == 40">
                <el-form-item label="减免金额" prop="reducePrice" :rules="[{ required: true, message: '请输入减免金额' }]">
                    <el-input class="max-w460" v-model="form.reducePrice" placeholder="请输入减免金额" type="number"></el-input>
                </el-form-item>
            </div>

            
            <div v-if="form.couponType === 20">
                <el-form-item label="折扣率" :label-width="formLabelWidth" prop="discount" :rules="[{ required: true, message: '请输入折扣率' }]">
                    <el-input type="number" :precision="1" :step="1" :min="0" :max="100" placeholder="请输入折扣率" v-model="form.discount" class="max-w460" @input="validateDiscount">
                        <template #append> % </template>
                    </el-input>
                    <div style="color: red" v-if="showDiscountError">
                        折扣率必须是1到100之间的整数
                    </div>
                    <div class="tips">折扣率范围1-100，95代表9.5折，0代表不折扣</div>
                </el-form-item>
            </div>
            <el-form-item label="核销券类型" prop="cancelType" :rules="[{ required: true, message: '请选择核销券类型' }]" v-if="form.couponType === 30">
                <el-radio-group v-model="form.cancelType">
                    <el-radio :label="0" border>肥料券</el-radio>
                    <el-radio :label="1" border>参观券</el-radio>
                    <el-radio :label="2" border>指导券</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="最多优惠多少元" v-if="form.couponType == 20">
                <el-input class="max-w460" v-model="form.bigPrice" placeholder="请输入金额" type="number"></el-input>
                <div class="tips">最大抵扣金额不能超出此金额，0代表不限制</div>
            </el-form-item>
            <el-form-item label="最低消费金额" :rules="[{ required: true, message: '请输入最低消费金额' }]" prop="minPrice">
                <el-input class="max-w460" v-model="form.minPrice" placeholder="请输入最低消费金额" type="number"></el-input>
            </el-form-item>
            <el-form-item label="到期类型">
                <el-radio-group v-model="form.expireType">
                    <el-radio :label="10" border>领取后生效</el-radio>
                    <el-radio :label="20" border>固定时间</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否可分享">
                <!-- 是否可以分享 0-不行 1-可以 -->
                <el-radio-group v-model="form.isCanShare">
                    <el-radio :label="0" border>否</el-radio>
                    <el-radio :label="1" border>是</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否可叠加使用">
                <el-radio-group v-model="form.superimpose">
                    <el-radio :label="0" border>否</el-radio>
                    <el-radio :label="1" border>是</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="充值活动充值金额" prop="rechargeMoney" :rules="[{ required: true, message: '请输入充值金额' }]" v-if="form.couponType === 60">
                <el-input-number :controls="false" v-model="form.rechargeMoney" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="充值满此金额送抵扣券" prop="rechargeLimitMoney" :rules="[{ required: true, message: '请输入充值满此金额送抵扣券' }]" v-if="form.couponType === 60">
                <el-input-number :controls="false" v-model="form.rechargeLimitMoney" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="使用规则">
                <el-input type="textarea" :rows="5" v-model="form.useRule" placeholder="请输入使用规则"></el-input>
            </el-form-item>
            <el-form-item label="优惠券价格" v-if="form.couponType === 50">
                <el-input-number v-model="form.couponPrice" :controls="false" :min="0"></el-input-number>
            </el-form-item>
            <div v-if="form.expireType == 10">
                <el-form-item label="有效天数" :rules="[{ required: true, message: '请输入有效天数' }]" prop="expireDay">
                    <el-input class="max-w460" v-model="form.expireDay" placeholder="请输入有效天数" type="number"></el-input>
                </el-form-item>
            </div>
            <div v-else>
                <el-form-item label="有效时间">
                    <el-date-picker class="max-w460" v-model="form.activeTime" type="daterange" align="right" unlink-panels value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions0"></el-date-picker>
                </el-form-item>
            </div>
            <el-form-item label="发放总数量 " prop="totalNum" :rules="[{ required: true, message: ' ' }]">
                <el-input class="max-w460" v-model="form.totalNum" placeholder="请输入发放总数量" type="number"></el-input>
                <div class="tips">限制领取的优惠券数量，-1为不限制</div>
            </el-form-item>
            <el-form-item label="是否显示在领券中心">
                <el-radio-group v-model="form.showCenter">
                    <el-radio :label="1" border>显示</el-radio>
                    <el-radio :label="0" border>不显示</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="使用条件">
                <el-radio-group v-model="form.freeLimit">
                    <el-radio :label="0" border>不限制</el-radio>
                    <el-radio :label="1" border>不可与促销同时使用</el-radio>
                    <el-radio :label="2" border>不可与等级优惠同时使用</el-radio>
                    <el-radio :label="3" border>不可于促销和等级优惠同时使用</el-radio>
                </el-radio-group>
                <div class="tips">促销是指满减，等级优惠券值商品的会员等级折扣</div>
            </el-form-item>
            <el-form-item label="排序">
                <el-input class="max-w460" type="number" v-model="form.sort" placeholder="请输入排序"></el-input>
            </el-form-item>
            <div class="common-form">适用商品</div>
            <el-form-item label="选择">
                <el-radio-group v-model="form.applyRange">
                    <el-radio :label="10" border>全部商品</el-radio>
                    <el-radio :label="20" border><span>指定商品</span></el-radio>
                    <el-radio :label="30" border><span>指定分类</span></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.applyRange == 20">
                <el-button class="mb10" @click="isProduct = true" type="primary" plain>添加商品</el-button>
                <el-table v-if="productList.length > 0" :data="productList" max-height="400" border style="width: 100%">
                    <el-table-column prop="productId" label="ID" width="180"></el-table-column>
                    <el-table-column prop="productName" label="商品名称" width="180"></el-table-column>
                    <el-table-column prop="image" label="图片">
                        <template #default="scope">
                            <img v-img-url="hasImages(scope.row.imagePath)" alt="" :width="80" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button @click="deleteClick(scope.$index)" type="text" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="" v-if="form.applyRange == 30">
                <el-button class="mb10" @click="isCategory = true" type="primary" plain>添加分类</el-button>
                <div>
                    <el-tag size="large" class="mr10 mb10" type="info" v-if="categoryList.first.length > 0"
                        v-for="(item, index) in categoryList.first" :key="item.categoryId">
                        {{ item.parent ? item.parent + "→" + item.name : item.name }}
                    </el-tag>
                    <el-tag size="large" class="mr10 mb10" type="info" v-if="categoryList.second.length > 0"
                        v-for="(item, index) in categoryList.second" :key="item.categoryId">
                        {{ item.parent ? item.parent + "→" + item.name : item.name }}
                    </el-tag>
                </div>
            </el-form-item>
            <!--提交-->
            <div class="common-button-wrapper">
                <el-button type="info" size="small" @click="cancelFunc" :loading="loading">取消</el-button>
                <el-button type="primary" size="small" @click="onSubmit" :loading="loading">提交</el-button>
            </div>
        </el-form>
        <!--选择商品-->
        <Product :isProduct="isProduct" :excludeIds="excludeIds" :islist="true" @closeDialog="closeProductFunc"></Product>
        <Category :isCategory="isCategory" :excludeIds="categoryIds" @close="closeCategoryFunc"></Category>
    </div>
</template>

<script>
import CouponApi from "@/api/coupon.js";
import Product from "@/components/product/Product.vue";
import Category from "@/components/category/category.vue";
import { formatModel } from '@/utils/base.js'
export default {
    components: {
        Product,
        Category,
    },
    props: {
        editId: {
            type: String,
            default: ''
        }
    },
    watch: {
        editId: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.form.couponId = val
                    this.getData(val)
                }
            }
        }
    },
    data() {
        return {
            activeName: "1",
            /*切换菜单*/
            activeIndex: "1",
            /*form表单数据*/
            form: {
                name: '',//优惠券名称
                color: 10, //优惠券颜色 
                couponType: 10, //优惠券类型 
                reducePrice: 0,//满减券-减免金额
                minPrice: 0,//	最低消费金额
                expireType: 10, //到期类型(10领取后生效 20固定时间)
                isCanShare: 0,//是否可分享
                superimpose: 0, //是否可以叠加使用 
                useRule: '', //使用规则
                expireDay: 0,//有效天数
                totalNum: 0, // 发放总数量(-1为不限制)
                showCenter: 0,//是否显示在领券中心
                freeLimit: 0, //使用条件
                sort: 1, //排序
                applyRange: 10, //使用范围
                discount: 0, //折扣率
                bigPrice: 0,//最多优惠多少元
                activeTime: [], //有效时间
                startTime: '',// 固定时间-开始时间
                endTime: '',//固定时间-结束时间
                cancelType: 0, //核销券类型0-肥料券 1-参观券 2-指导券
                couponPrice: 0,//优惠券价格
                rechargeMoney: 0, //充值活动充值金额
                rechargeLimitMoney: 0, //充值满此金额送抵扣券
                couponId: '',
                productIds:'',
                categoryListFirst:[],
                categoryListSecond:[]

            },
            loading: false,
            pickerOptions0: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的
                },
            },
            isCategory: false,
            isProduct: false,
            excludeIds: [],
            productList: [],
            categoryList: {
                first: [],
                second: [],
            },
            categoryListFirst: [],
            categoryListSecond: [],
            couponOptions: [
                { name: '满减券', value: 10 },
                { name: '折扣券', value: 20 },
                { name: '核销券', value: 30 },
                { name: '商品券', value: 40 },
                { name: '购买券', value: 50 },
                { name: '充值券', value: 60 }
            ],

        };
    },
    created() { },
    methods: {
        hasImages(e) {
            if (e) {
                return e;
            } else {
                return "";
            }
        },
        validateDiscount(value) {
            const discountPattern = /^[1-9]\d?$|^100$/;
            if (!discountPattern.test(value)) {
                this.showDiscountError = true;
            } else {
                this.showDiscountError = false;
                this.form.discount = value;
            }
        },
        getData(id) {
            let self = this;
            self.loading = true
            CouponApi.couponDetail({ id: id, }, true)
                .then((res) => {
                    const { data } = res
                    const newData = Object.assign({}, data)
                    self.form = newData
                    console.log('newdata', newData)
                    //处理商品逻辑
                    if (newData.applyRange === 30) {
                        //指定分类 
                        self.categoryList = newData.categoryList
                    }
                    //指定商品
                    if (newData.applyRange === 20)
                        self.productList = newData.productList
                    self.loading = false;
                    //设置时间
                    if(newData.expireType === 20) 
                        self.form.activeTime = [newData.startTime, newData.endTime]
                })
                .catch((error) => {
                    console.log(error);
                    self.loading = false;
                });
        },
        /*添加用户*/
        onSubmit() {
            let self = this;
            let form = self.form;
            console.log('提交数据', form)
            self.form.productIds = []
            self.form.productList=[]
            if (form.applyRange === 20) {
                self.form.productIds = self.productList.map(f => f.productId)
                self.form.productList =  self.productList
            }
            if (form.applyRange === 30) {
                if (self.categoryList) {
                    const { first, second } = self.categoryList
                    if (first)
                        form.categoryListFirst = first.map(f => f.categoryId)
                    if (second)
                        form.categoryListSecond = second.map(f => f.categoryId)
                }
            }
            //处理时间
            self.form.startTime =''
            self.form.endTime =''
            if(self.form.expireType === 20) {
                if(self.form.activeTime && self.form.activeTime.length>0) {
                self.form.startTime = self.form.activeTime[0]
                self.form.endTime = self.form.activeTime[1]
            }
            }
           
             self.$refs.form.validate((valid) => {
                if (valid) {
                    console.log('提交数据', form)
                    self.loading = true;
                    if (form.couponId) {
                        CouponApi.editCoupon(form, true)
                            .then((data) => {
                                self.loading = false;
                                ElMessage({
                                    message: "恭喜你，更新成功",
                                    type: "success",
                                });
                                self.$router.push("/discount/coupon/index");
                            })
                            .catch((error) => {
                                self.loading = false;
                            });
                    } else {
                        CouponApi.addCoupon(form, true)
                            .then((data) => {
                                self.loading = false;
                                ElMessage({
                                    message: "恭喜你，添加成功",
                                    type: "success",
                                });
                                self.$router.push("/discount/coupon/index");
                            })
                            .catch((error) => {
                                self.loading = false;
                            });
                    }

                }
            });
        },
        closeCategoryFunc(e) {
           console.log('分类选择',e)
            let self = this;
            self.isCategory = false;
            if (e) {

                self.categoryList = e;
                self.categoryListFirst = [];
                e.first.forEach((item, index) => {
                    self.categoryListFirst.push(item.categoryId);
                });
                self.categoryListSecond = [];
                e.second.forEach((item, index) => {
                    self.categoryListSecond.push(item.categoryId);
                });
            }
        },
        /*关闭商品*/
        closeProductFunc(e) {
            let self = this;
            self.isProduct = e.openDialog;
            if (e.type == "success") {
                e.params.forEach((item, index) => {
                    let params = {
                        productId: item.productId,
                        productName: item.productName,
                        imagePath: item.image,
                    };
                    self.productList.push(params);
                });
            }
        },
        /*取消*/
        cancelFunc() {
            this.$router.push({
                path: "/discount/coupon/index",
            });
        },
        deleteClick(e) {
            this.excludeIds.splice(e, 1);
            this.productList.splice(e, 1);
        },
    },
};
</script>

<style lang="scss" scoped>
.mb10 {
    margin-bottom: 10px;
}

.product-add {
    padding-bottom: 50px;
}

.tips {
    color: #ccc;
}
</style>